from flask import Blueprint, request, jsonify
from ..utils.repository import Repository

repository_bp = Blueprint('repository', __name__)

@repository_bp.route('/repository/songs', methods=['GET'])
def get_songs():
    """获取歌曲列表，支持分页和过滤"""
    try:
        # 获取分页参数，默认第1页，每页20条
        page = int(request.args.get('page', 1))
        page_size = int(request.args.get('page_size', 20))
        
        # 获取过滤参数
        filters = {}
        if 'song_name' in request.args:
            filters['song_name'] = request.args.get('song_name')
        if 'artist_name' in request.args:
            filters['artist_name'] = request.args.get('artist_name')
            
        # 调用Repository方法获取歌曲列表
        result = Repository.get_songs(page=page, per_page=page_size, filters=filters)
        return jsonify(result)
    
    except Exception as e:
        return jsonify({'code': 500, 'message': f'获取歌曲列表失败: {str(e)}'})

@repository_bp.route('/repository/songs/<song_id>', methods=['GET'])
def get_song_details(song_id):
    """获取歌曲详情"""
    try:
        result = Repository.get_song_details(song_id)
        return jsonify(result)
    
    except Exception as e:
        return jsonify({'code': 500, 'message': f'获取歌曲详情失败: {str(e)}'})

@repository_bp.route('/repository/artists', methods=['GET'])
def get_artists():
    """获取歌手列表，支持分页和过滤"""
    try:
        page = int(request.args.get('page', 1))
        page_size = int(request.args.get('page_size', 20))
        name_filter = request.args.get('name', None)
        
        result = Repository.get_artists(page=page, per_page=page_size, name_filter=name_filter)
        return jsonify(result)
    
    except Exception as e:
        return jsonify({'code': 500, 'message': f'获取歌手列表失败: {str(e)}'})

@repository_bp.route('/repository/artists/<artist_id>', methods=['GET'])
def get_artist_details(artist_id):
    """获取歌手详情"""
    try:
        result = Repository.get_artist_details(artist_id)
        return jsonify(result)
    
    except Exception as e:
        return jsonify({'code': 500, 'message': f'获取歌手详情失败: {str(e)}'})